package aimozg.joglfw.figures;

import aimozg.joglfw.GLColor;
import aimozg.joglfw.GLPoint;
import aimozg.joglfw.JoglApplication;
import com.sun.opengl.util.BufferUtil;

import javax.media.opengl.GL;
import java.nio.DoubleBuffer;

/**
 * Created by IntelliJ IDEA.
 * User: aimozg
 * Date: 06.01.11
 * Time: 14:12
 */
public class Primitive {
	private final JoglApplication.PrimitiveType type;
	private final ColorRef colorRef;
	//private final GLPoint[] points;
	private final DoubleBuffer buffer;
	private final int nPoints;

	public Primitive(JoglApplication.PrimitiveType type, ColorRef colorRef, GLPoint... points) {
		this.type = type;
		this.colorRef = colorRef;
		//this.points = points;
		nPoints = points.length;
		this.buffer = BufferUtil.newDoubleBuffer(3 * nPoints);
		for (GLPoint pt : points) {
			buffer.put(pt.x).put(pt.y).put(pt.z);
		}
	}

	public Primitive(JoglApplication.PrimitiveType type, GLColor color, GLPoint... points) {
		this(type, new ColorRef(color), points);
	}

	public Primitive(JoglApplication.PrimitiveType type, String color, GLPoint... points) {
		this(type, new ColorRef(color), points);
	}

	private void render(JoglApplication app, Palette palette, boolean fast) {
		app.setColor(colorRef.get(palette));
		if (!fast) {
			app.gl().glEnableClientState(GL.GL_VERTEX_ARRAY);
		}
		buffer.rewind();
		app.gl().glVertexPointer(3, GL.GL_DOUBLE, 0, buffer);
		app.gl().glDrawArrays(type.glConstant, 0, nPoints);
		if (!fast) {
			app.gl().glDisableClientState(GL.GL_VERTEX_ARRAY);
		}
	}

	public void render(JoglApplication app, Palette palette) {
		render(app, palette, false);
	}

	public void renderFast(JoglApplication app, Palette palette) {
		render(app, palette, true);
	}
}
